import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { loginAPI } from '@/apis/login'


import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'

export const useLoginStore = defineStore('login', () => {
const router = useRouter()
  const UserList = ref([]) // 登录后的用户信息
  // 获取登录后的用户信息并进行持久化存储
  const getUser = async (account, password) => {
    const res = await loginAPI(account,password)
    UserList.value = res.data.result
    router.replace('/') // 登录成功跳转
    ElMessage({type: 'success', message: '登录成功'})
  }

  // 退出登录清除登录信息
  const removeUser = () => {
    UserList.value = {}
    ElMessage({type: 'error', message: '退出登录成功'})
  }

  // 如果是401 就清空数据 跳转到登录页面
  const checkLogin = () => {
    UserList.value = {}
    ElMessage({type: 'success', message: '用户登录失效，请重新登录'})
    router.replace('/login')
  }


  return { UserList, getUser, removeUser, checkLogin}
},
  {
    persist: true // 开启持久化
  }
)

